package com.test.deviceinfo.util;

import cn.hutool.core.util.StrUtil;
import com.test.deviceinfo.info.PcInfo;
import com.test.deviceinfo.info.UserInfo;

import java.io.*;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Scanner;
import java.util.logging.Logger;

public class GetCommonInfo {

    static Logger logger = Logger.getLogger(GetCommonInfo.class.getName());

    /**
     * 系统信息
     */
    public static void getLocalHost(){
        try{
            InetAddress ip = InetAddress.getLocalHost();
            String localName = ip.getHostName();
            String osName = System.getProperty("os.name");
            String userName = System.getProperty("user.name");
            String osVersion = System.getProperty("os.version");
            String osArch = System.getProperty("os.arch");

            System.out.println("当前用户：" + userName);
            System.out.println("主机名称：" + localName);
            System.out.println("主机系统：" + osName);
            System.out.println("系统版本：" + osVersion);
            System.out.println("系统架构：" + osArch);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 用户信息
     * @param userInfo
     */
    public static void getUserInfo(UserInfo userInfo){
        try{
            String userName = System.getProperty("user.name");
            String userHome = System.getProperty("user.home");
            String userDir = System.getProperty("user.dir");

            System.out.println("当前用户：" + userName);
            System.out.println("用户主目录："+ userHome);
            System.out.println("当前工作目录："+ userDir);

            userInfo.setWorkDir(userDir);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 主板序列号
     * @return
     */
    public static void getCpuInfo(PcInfo pcInfo) throws IOException {
        Process process = Runtime.getRuntime().exec(
                new String[] { "wmic", "cpu", "get", "ProcessorId" });
        process.getOutputStream().close();
        Scanner sc = new Scanner(process.getInputStream());
        String property = sc.next();
        String serial = sc.next();
        pcInfo.setMainBordId(serial);
    }

    /**
     * ip和mac
     * @param info
     */
    public static void getWindowsIpAndMac(PcInfo info){
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            // 遍历网卡接口
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = allNetInterfaces.nextElement();
                // 去除回环接口，子接口，未运行和接口
                if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
                    continue;
                }

                // 重点来了：“经验”之谈
                // 为了过滤掉虚拟机的网卡，可以通过网卡名来进行基础过滤。windows主机ip对应的网卡名会包含下面三个：Intel  无线、Realtek  网线、Ethernet  兼容xp系统
                if (!netInterface.getDisplayName().contains("Intel")
                        && !netInterface.getDisplayName().contains("Realtek")
                        && !netInterface.getDisplayName().contains("Ethernet")) {
                    continue;
                }

                String ip = "";
                String mac = "";
                String niName = "";
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress ia = addresses.nextElement();
                    // 去除本地回环地址，子接口，未运行和地址
                    if (ia != null && !ia.isLoopbackAddress() && ia.isSiteLocalAddress() && !ia.isAnyLocalAddress()) {
                        // 判断是否是ip v4地址
                        if (ia instanceof Inet4Address) {
                            ip = ia.getHostAddress();
                            // 获取MAC地址
                            mac = getMac(ia);
                            niName = netInterface.getName();
                            if (StrUtil.isNotBlank(ip) && StrUtil.isNotBlank(mac) && StrUtil.isNotBlank(niName)){
                                System.out.println("当前网卡："+niName);
                                System.out.println("当前主机ip："+ip);
                                System.out.println("当前主机MAC："+mac);

                                info.setMac(mac);
                                info.setIp(ip);
                                return;
                            }
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    public static String getMac(InetAddress ia){
        try {
            //获取网卡，获取地址
            byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
            StringBuffer sb = new StringBuffer();
            if (mac != null && mac.length>0){
                for(int i=0; i<mac.length; i++) {
                    if(i!=0) {
                        sb.append("-");
                    }
                    //字节转换为整数
                    String str = Integer.toHexString(mac[i] & 0xff);
                    if(str.length()==1) {
                        sb.append("0").append(str);
                    }else {
                        sb.append(str);
                    }
                }
            }
            return sb.toString().toUpperCase();
        } catch (SocketException e) {
            e.printStackTrace();
            return null;
        }
    }
}
